<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
<!--      <template #menu="{ model, field }">-->
<!--        <BasicTree-->
<!--          v-model:value="model[field]"-->
<!--          :treeData="treeData"-->
<!--          :fieldNames="{ title: 'menuName', key: 'id' }"-->
<!--          checkable-->
<!--          toolbar-->
<!--          title="菜单分配"-->
<!--        />-->
<!--      </template>-->
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './role.data';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicTree, TreeItem } from '@/components/Tree';
  import { createGroupChatApi,detailApi,editApi } from '@/api/sys/chatGroup';

  import {useMessage} from "@/hooks/web/useMessage";

  import {useUserStore} from "@/store/modules/user";
  const userStore = useUserStore();

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const treeData = ref<TreeItem[]>([]);
  const { createMessage } = useMessage();

  const openConversationId =ref("");
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [register, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //打开弹层后的回调
    resetFields();
    setModalProps({ confirmLoading: false });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    // if (unref(treeData).length === 0) {
    //   treeData.value = (await getMenuList()) as any as TreeItem[];
    // }
    isUpdate.value = !!data?.isUpdate;
    openConversationId.value="";
    if (unref(isUpdate)) {

     // console.log("---data.record:",data.record)
      openConversationId.value=data.record.openConversationId;
      let json={
        openConversationId:openConversationId.value
      };

      detailApi(json).then((res) => {
         console.log("---res::",res)
        if(res.code==200){
          let item=res.data;

          if(item){
            setFieldsValue(item);
            userStore.setChatIsUpdate(true);
           // getBooksFn(item);
            // if(item.owner){
            //
            // }
          }
        }else{
          createMessage.error(res.message);

        }
      })

    }else{
      //新增
      let item={
        totalType:2,
        templatePrefix:"创造时间价值，成就幸福人生。#startDate起，打卡第#dateNum天。#month月#start日～#end日\n" +
          "[鲜花][鲜花][鲜花][鲜花][鲜花][鲜花][鲜花][鲜花][鲜花][鲜花][鲜花]",
        templateSuffix:"[胜利][胜利][胜利][胜利][胜利][胜利][胜利][胜利][胜利][胜利]\n" +
          "       同时把今天学习的智慧文化功课回向给众生，衷心祝福世界和平，生态文明，国泰民安，家人、顾客及同学们身体健康，阖家欢乐，事业有成，五福临门；恒丽集团蒸蒸日上！[烟花][烟花][烟花]\n" +
          "[灯笼][灯笼][灯笼]",
        nameSuffix:"[鲜花]"
      }
      setFieldsValue(item);
      userStore.setChatIsUpdate(false);

    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增班级' : '编辑班级'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      values.openConversationId=openConversationId.value;
      // console.log("---values")
      // console.log(values);
      console.log("---handleSubmit::isUpdate",isUpdate.value)
      if (isUpdate.value) {
        editFn(values);
      }else{
        createFn(values)
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function createFn(values){
    createGroupChatApi(values).then((res) => {
      // console.log("---res::",res)
      if(res.code==200){
        createMessage.success(res.message);
      }else{
        createMessage.error(res.message);
      }
    })
      .catch((res) => {
        createMessage.error(res.message);
      })
      .finally(() => {
        closeModal();
        emit('success');
      });
  }

  function editFn(values){
    editApi(values).then((res) => {
      // console.log("---res::",res)
      if(res.code==200){
        createMessage.success(res.message);
      }else{
        createMessage.error(res.message);
      }
    })
      .catch((res) => {
        createMessage.error(res.message);
      })
      .finally(() => {
        closeModal();
        emit('success');
      });
  }



</script>
